import json
import time
import logging
import datetime
import pandas as pd

import QUANTAXIS as QA
from QUANTAXIS.QAARP import QA_Risk
from QIFIAccount.QIFIAccount.QARealtimeStockSim import QIFI_StockSIM_Account
from QAStrategy.QAStrategy.mc.muti_freq_strategy import MutiFreqStrategy


def main():
    # account
    username = 'admin'
    password = 'admin'

    # strategy
    print('start execute strategy')
    today = datetime.date.today()
    last_week = datetime.date.today() + datetime.timedelta(days=-30)
    last_year = datetime.date.today() + datetime.timedelta(days=-365)

    start = last_week.strftime('%Y-%m-%d')
    end = today.strftime('%Y-%m-%d')
    end = QA.QA_util_get_pre_trade_date(end, n=1)
    start = '2020-11-20'
    end = '2021-02-18'

    # codes
    codes = ['510050', '510300']

    # frequency
    frequences = [
                  QA.FREQUENCE.FIVE_MIN,
                  # QA.FREQUENCE.FIFTEEN_MIN,
                  # QA.FREQUENCE.THIRTY_MIN,
                  # QA.FREQUENCE.SIXTY_MIN,
                  QA.FREQUENCE.DAY,
                  # QA.FREQUENCE.WEEK,
                  # QA.FREQUENCE.MONTH,
                  # QA.FREQUENCE.YEAR,
                  QA.FREQUENCE.ONE_MIN  # 多周期策略必须包含1min，触发on_bar
                  ]

    strategy = MutiFreqStrategy(username='muti_freq_backtest1', password='123456', code=codes,
                         market=QA.MARKET_TYPE.INDEX_CN, start=start, end=end, show_trade=True,
                         min_trade_money=3000, once_trade_money=10000,
                         frequences=frequences, strategy_id=username, init_cash=1e5)
    strategy.run_backtest()
    # strategy.plot_grid()
    risk = QA_Risk(strategy.acc)
    # print(risk.risk_message)
    # s = pd.Series(risk.risk_message)
    # s['start'] = start
    # print(s)
    df = pd.DataFrame.from_dict(risk.risk_message, orient='index', columns=['values']).T
    # df.to_csv('bt_result.csv')
    risk.plot_assets_curve()
    # risk.plot_dailyhold()
    # risk.plot_signal()

if __name__ == "__main__":
    try:
        from QUANTAXIS_RealtimeCollector.QARealtimeCollector.utils.logconf import update_log_file_config
        logfile = 'stock.backtest.log'
        logging.config.dictConfig(update_log_file_config(logfile))
    except Exception as e:
        print(e.__str__())
    main()